/* global plupload */

/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

;
(function ($) {
    // 插件的定义
    $.fn.uploader = function (options) {
        // build main options before element iteration
        var opts = $.extend({}, $.fn.uploader.defaults, options);

        // iterate and reformat each matched element
        return this.each(function () {
            var $this = $(this);
            // build element specific options
            var o = $.metadata ? $.extend({}, opts, $this.data()) : opts;
            $.fn.uploader.ratio = 100 / o.ratio;


            var previewContainer = $('#preview-container');
            // update element styles
            //Plupload
            var uploader = new $.fn.uploader.plupload.Uploader({
                runtimes: 'html5,flash,silverlight,html4',
                browse_button: 'selectfiles',
                id: o.id,
                input_name: o.inputName,
                multi_selection: false,
                container: this,
                url: o.url,
                filters: {
                    mime_types: o.mimeTypes,
                    max_file_size: o.maxFileSize,
                    prevent_duplicates: true //不允许选取重复文件
                },
                init: {
                    FilesAdded: function (up, files) {
                        if (!o.multiSelection) {
                            up.disableBrowse(true);
                            previewContainer.removeClass('hide');
                            addClass(up.settings.browse_button[0], 'hide');
                        }
                        plupload.each(files, function (file) {
                            previewPanel(up, file, function (element) {
                                previewContainer.append(element);
                            });
                        });
                    },
                    PostInit: function (up) {
                        up.settings.container.lastChild.style.display = 'none';
                        up.settings.browse_button[0].querySelector('.square-block-dummy').style.marginTop = $.fn.uploader.ratio + '%';

                        document.getElementById('preview-container').innerHTML = '';
                    },
                    BeforeUpload: function (up, file) {
                        console.log('BeforeUpload');
                        set_upload_param(up, file.name, true);
                        var previewItem = $('#preview-' + file.id);
                        previewItem.addClass('uploading');
                        previewItem.find('.file-actions').html('<span class="uploading-text">正在上传...</span>');

                    },
                    UploadProgress: function (up, file) {
                        console.log(file.percent);
                        var progBar = $('#progress' + file.id + ' span');
                        progBar.width(file.percent + '%');
                        progBar.attr("aria-valuenow", file.percent);
                    },
                    FileUploaded: function (up, file, info) {
                        var previewItem = $('#preview-' + file.id);
                        previewItem.removeClass('uploading');
                        var text = '';
                        if (info.status === 200) {
                            previewItem.find('.file-actions').html('<span class="upload-success">上传成功</span>');
                            previewItem.find('input.plupload_file_input').val(get_uploaded_object_name(file.name));
                            text = 'upload to oss success, object name:'
                                    + get_uploaded_object_name(file.name)
                                    + ' 回调服务器返回的内容是:'
                                    + info.response;
                        } else if (info.status === 203) {
                            previewItem.find('.file-actions').html('<span class="upload-error">回调失败</span>');
                            text = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:'
                                    + info.response;
                        } else {
                            previewItem.find('.file-actions').html('<span class="upload-error">上传失败</span>');
                            text = info.response;
                        }
                        if (text) {
                            previewItem.find('.square-block-error').removeClass('hide').html(text);
                        }
                    },
                    Error: function (up, err) {
//                        var previewItem = $('#preview-' + file.id);
                        console.log(err.response);
//                        if (err.code === -600) {
//                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
//                        } else if (err.code === -601) {
//                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
//                        } else if (err.code === -602) {
//                            document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
//                        } else {
//                            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
//                        }
                    }
                }
            });
            uploader.init();
        });
    };

    var hasClass = function (e, cls) {
        return e.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
    };

    //为指定的dom元素添加样式
    var addClass = function (e, cls) {
        if (!hasClass(e, cls)) {
            e.className += " " + cls;
        }
    };
    //删除指定dom元素的样式
    var removeClass = function (e, cls) {
        if (hasClass(e, cls)) {
            var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
            e.className = e.className.replace(reg, " ");
        }
    };

    var getSignature = function () {
        // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
        now = timestamp = Date.parse(new Date()) / 1000;
        if (expire < now + 3) {
            var body = {};
            $.ajax({
                url: '/attachs/authent',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (data) {
                    body = data;
                },
                error: function (json) {
                    alert("Your browser does not support XMLHTTP.");
                }
            });
            if (body) {
                host = body.host;
                token = body.token;
                policyBase64 = body.policy;
                accessid = body.accessid;
                signature = body.signature;
                expire = parseInt(body.expire);
                callbackbody = body.callback;
                key = body.dir;
                return true;
            } else {
                return false;
            }
        }
        return false;
    };

    var random_string = function (len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    var get_suffix = function (filename) {
        pos = filename.lastIndexOf('.');
        suffix = '';
        if (pos !== -1) {
            suffix = filename.substring(pos);
        }
        return suffix;
    };

    var calculate_object_name = function (filename) {
        if (g_object_name_type === 'local_name') {
            g_object_name += "${filename}";
        } else if (g_object_name_type === 'random_name') {
            suffix = get_suffix(filename);
            g_object_name = key + random_string(10) + suffix;
        }
        return '';
    };

    var get_uploaded_object_name = function (filename) {
        if (g_object_name_type === 'local_name') {
            tmp_name = g_object_name;
            tmp_name = tmp_name.replace("${filename}", filename);
            return tmp_name;
        } else if (g_object_name_type === 'random_name') {
            return g_object_name;
        }
    };

    var set_upload_param = function (up, filename, ret) {
        if (ret === false) {
            ret = getSignature();
        }
        g_object_name = key;
        if (filename !== '') {
            suffix = get_suffix(filename);
            calculate_object_name(filename);
        }
        var newsparams = {
            'key': g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'x-oss-security-token': token,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature
        };
        up.setOption({
            url: host,
            multipart_params: newsparams
        });
        up.start();
    };

    /**
     * accessid 
     */
    var accessid = '';

    /**
     * accesskey 
     */
    var accesskey = '';

    /**
     * 已经设置的SKU值 
     */
    var host = '';

    /**
     * 已经设置的SKU值 
     */
    var token = '';

    /**
     * 已经设置的SKU值 
     */
    var policyBase64 = '';

    /**
     * 已经设置的SKU值 
     */
    var signature = '';

    /**
     * 已经设置的SKU值 
     */
    var callbackbody = '';

    /**
     * 已经设置的SKU值 
     */
    var filename = '';

    /**
     * 已经设置的SKU值 
     */
    var key = '';

    /**
     * 已经设置的SKU值 
     */
    var expire = 0;

    /**
     * 已经设置的SKU值 
     */
    var g_object_name = '';

    /**
     * 对象随机命名 
     */
    var g_object_name_type = 'random_name';


    /**
     * 已经设置的SKU值 
     */
    var timestamp = Date.parse(new Date()) / 1000;

    /**
     * 已经设置的SKU值 
     */
    var now = timestamp;

    var videoTypes = /^video\/.*$/;

    var imageTypes = /^image\/.*$/;

    /**
     * 创建文件面板
     */
    var fileNodeBox = function (file, callback) {
        var _previewElement = null;
        var url = URL.createObjectURL(file.getNative());
        if (imageTypes.test(file.type)) {
            _previewElement = document.createElement('img');
            _previewElement.src = url;
        } else if (videoTypes.test(file.type)) {
            _previewElement = document.createElement('video');
            _previewElement.src = url;
            _previewElement.controls = true;
        } else {
            _previewElement = document.createElement('div');
            _previewElement.className = 'file file-' + file.type.replace(/\//g, "-");
        }
        callback(_previewElement);
    };

    /**
     * 创建上传进度条
     */
    var previewProgress = function (file, callback) {
        var progressElement = document.createElement('div');
        progressElement.id = 'progress' + file.id;
        progressElement.className = 'progress';
        var progressBarElement = document.createElement('span');
        progressBarElement.className = 'progress-bar';
        progressBarElement.style.width = '0%';
        progressBarElement.setAttribute('role', 'progressbar');
        progressBarElement.setAttribute('aria-valuenow', '0');
        progressBarElement.setAttribute('aria-valuemin', '0');
        progressBarElement.setAttribute('aria-valuemax', '100');
        progressElement.append(progressBarElement);
        callback(progressElement);
    };

    /**
     * 创建预览模版 
     */
    var previewPanel = function (uploader, file, callback) {

        var el = document.createElement('div');
        el.id = 'preview-' + file.id;
        el.className = 'preview-item';
        el.innerHTML = '<div class="square-block">'
                + '<div class="square-block-error hide"></div>'
                + '<div class="square-block-dummy"></div>'
                + '<div class="square-block-box"></div>'
                + '</div>'
                + '<div class="file-data">'
                + '<div class="file-info">'
                + '<h3>' + file.name + '</h3>'
                + '<p>' + $.fn.uploader.plupload.formatSize(file.size) + '</p>'
                + '</div>'
                + '<div class="file-actions">'
                + '<button type="button" id="postfiles" class="btn btn-sm btn-success btn-upload hide">上传</button>'
                + '</div>'
                + '</div>';
        el.querySelector('.square-block-dummy').style.marginTop = $.fn.uploader.ratio + '%';
        fileNodeBox(file, function (node) {
            el.querySelector('.square-block-box').append(node);
        });
        previewProgress(file, function (element) {
            el.querySelector('.file-data').append(element);
        });

        var inputElement = document.createElement('input');
        inputElement.id = uploader.settings.id + '-' + file.id;
        inputElement.name = uploader.settings.input_name;

        inputElement.value = '';
        inputElement.type = 'hidden';
        inputElement.className = 'plupload_file_input';
        el.append(inputElement);

        var btnElement = document.createElement('button');
        btnElement.id = 'btn-upload-' + file.id;
        btnElement.className = 'btn btn-sm btn-success btn-upload';
        btnElement.innerHTML = '上传';

        btnElement.onclick = function () {
            set_upload_param(uploader, '', false);
            return false;
        };
        el.querySelector('.file-actions').append(btnElement);

        callback(el);
    };

    // 定义暴露format函数
    $.fn.uploader.format = function (txt) {
        return '<strong>' + txt + '</strong>';
    };

    // 比例
    $.fn.uploader.ratio = 1;
    // 定义暴露format函数
    $.fn.uploader.plupload = window.plupload;

    // 插件的defaults
    $.fn.uploader.defaults = {
        id: '',
        inputName: '',
        authFilter: true,
        multiSelection: false,
        ratio: 1,
        url: 'http://oss.aliyuncs.com',
        //最大只能上传10mb的文件
        maxFileSize: '100mb',
        //只允许上传图片和zip文件
        mimeTypes: [
            {title: "Video files", extensions: "mp4"}
        ]
    };
    // 闭包结束
})(jQuery);